import groovy.time.*

class FeedCollectorService {

  boolean transactional = true
  
  public void updateAllFeeds() {
    log.info "Updating all Feeds..."
    use(org.codehaus.groovy.runtime.TimeCategory){
      def now = new Date()
      FeedInfo.list().each {feedInfo ->
        if ((feedInfo.lastUpdated + feedInfo.updateFrequency.minutes) < now) {
          updateFeed(feedInfo)
        }
      }
    }
  }


  public String updateFeed(FeedInfo feedInfo) {
    Date now = new Date()
    String returnValue = ""
    int newCounter = 0
    int existCounter = 0

    if (feedInfo) {
      try {
        def feedString = feedInfo.feedUrl.toURL().text
        def feed = new XmlSlurper().parseText(feedString)
        if (feed.entry.size() > 0) {
          log.info "Now updating feed '$feedInfo' (Atom feed)"
          feed.entry.list().reverse().each {entry ->
            Date date = new Date(entry.published.toString())
            log.debug "Atom Feed found: ${entry.title}, Link: ${entry.link}, Published: ${entry.published} (parsed as date: ${date})"
            if (entry.link) {
              if (!Message.findByLink("${entry.link}")) {
                String entryText = entry.title
                if (entry.link.contains('twitter')) entryText = cleanUpTwitterString(entry.title)
                new Message(user: feedInfo.user, content: entryText, medium: "MoTS Atom Feed Aggregator from ${feedInfo.feedName}", link: "${entry.link}", dateCreated: date).save()
                newCounter++
              } else {
                existCounter++;
              }
            }
          }
        } else if (feed.channel.item.size() > 0) {
          log.info "Now updating feed '$feedInfo' (RSS2 feed)"
          feed.channel.item.list().reverse().each {entry ->
            Date date = new Date(entry.pubDate.toString())
            log.debug "RSS2 Feed found: ${entry.title}, Link: ${entry.link}, Published: ${entry.pubDate} (parsed as date: ${date})"
            if (entry.link) {
              if (!Message.findByLink("${entry.link}")) {
                String entryText = entry.title
                if (entryText.toLowerCase().contains('twitter')) entryText = cleanUpTwitterString(entryText)
                new Message(user: feedInfo.user, content: entryText, medium: "MoTS RSS2 Feed Aggregator from ${feedInfo.feedName}", link: "${entry.link}", dateCreated: date).save()
                newCounter++
              } else {
                existCounter++
              }
            }
          }
        }
        feedInfo.lastUpdated = now
        feedInfo.merge()
        returnValue = "Feed update completed. ${newCounter} new and ${existCounter} existing entries found"
      } catch (IOException e) {
        returnValue = "An error occurred while retrieving '${feedInfo?.feedUrl}'. Make sure that this URL is correct and not password protected: ${e}"
        log.warn(returnValue)
      } catch (Exception e) {
        returnValue = "An error occurred while updating feed ${feedInfo.feedUrl}: ${e}"
        log.error(returnValue, e)
      }
    } else {
      returnValue = "No feed to update found."
    }
    return returnValue
  }

  def cleanUpTwitterString = {String message ->
    return message.replaceFirst('.*:', '')    
  }
}
